public class Test {
    //复杂数组对象练习 --- 添加和遍历
    public static void main(String[] args) {
        // 1.创建一个长度为三的数组
        Student[] arr = new Student[3];

        // 2.创建学生对象
        Student stu1 = new Student(1, "zhangsan", 23);
        Student stu2 = new Student(2, "lisi", 24);
        Student stu3 = new Student(3, "wangwu", 25);

        // 3.把学生对象添加到数组当中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;

        // 4.再次创建一个学生对象
        Student stu4 = new Student(4, "zhaoliu", 26);

        // 5.唯一性判断
        boolean flag = contains(arr, stu4.getId());
        // 5.1已存在 --- 提示已存在
        if (flag) {
            System.out.println("当前id已存在,请重新选择id");
        } else {
            // 5.2不存在 --- 添加学生对象
            // 6.添加学生对象
            int count = countArr(arr);
            if (count == arr.length) {
                // 6.1老数组已经存满 --- 创建一个新数组并在新数组中进行添加
                Student[] newArr = createNewArr(arr);
                newArr[count] = stu4;
                printArr(newArr);
            } else {
                // 6.2老数组没有存满 --- 直接进行添加
                arr[count] = stu4;
                printArr(arr);
            }


        }


    }

    // 打印学生信息
    public static void printArr(Student[] arr) {
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if (stu != null) {
                System.out.println(stu.getId() + "," + stu.getName() + "," + stu.getAge());
            }
        }
    }


    // 创建一个新数组(新数组的长度是老数组的长度 + 1)
    public static Student[] createNewArr(Student[] arr) {
        Student[] newArr = new Student[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;

    }

    // 对数组是否存满进行判断
    public static int countArr(Student[] arr) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != null) {
                count++;
            }
        }
        return count;

    }

    // id唯一性判断
    public static boolean contains(Student[] arr, int id) {

        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if (stu != null) {
                int sid = stu.getId();
                if (sid == id) {
                    return true;
                }
            }
        }
        return false;
    }
}
